<script setup lang='ts' name="protocol-management-add">
import type { VxeTableInstance } from 'vxe-table'

import { useGetAgreementMetaInfo } from '@fl/api/purchase'
import { SearchTable } from '@fl/components'
import ButtonItem from '@fl/components/button-item.vue'
import { cloneDeep } from 'lodash-es'
import NP from 'number-precision'
import { computed, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'

import { agreementTypeOptions } from '../constant'
import { filterLabel } from '../heler'
import DirectOrder from './direct-order.vue'
// import { useForm } from './hooks/use-form'
import { useTable } from './hooks/use-table'
import SelectGoods from './select-goods.vue'
import UploadOrder from './upload-order.vue'

const { params } = useRoute()
const { back } = useRouter()
const agreementId = computed(() => {
    return params.id
})
const orderId = ref('')
const orderData = ref(null)
const { data: agreementData, isLoading: agreementLoading } = useGetAgreementMetaInfo(agreementId)

const { btns, footBtn, gridOptions, toolBtn } = useTable()

// const { form, reset, schema } = useForm(instance)
const SelectGoodsRef = ref<InstanceType <typeof SelectGoods> | null>(null)
const tableRef = ref<VxeTableInstance<any>>()

const visible = ref(false)
const detail = ref<any>({
    isFile: false,
})

const rules = {
    isFile: [
        { required: true },
    ],
}
const show = ref(false)
const showProductSelect = ref(true)
const totalPrice = computed(() => {
    if (gridOptions?.data) {
        const sum = gridOptions?.data.reduce((accumulator, currentValue) => accumulator + ((currentValue.quantity ?? 0) * currentValue.agreementPrice), 0)
        return NP.round(sum, 2)
    }
    return 0
})

function doAction(item: any, row?: any) {
    switch (item.value) {
        case 'select':
            show.value = true
            break
        case 'import': // 导入商品
            visible.value = true
            break
        case 'delete':
            removeRow(row)
            break
        case 'add':
            goTo()
            break

        default:
            break
    }
}
function removeRow(row: any) {
    const removeGirdIndex = gridOptions.data?.findIndex((item: any) => item.id === row.id)
    if (removeGirdIndex > -1) {
        gridOptions.data?.splice(removeGirdIndex, 1)
    }
}
function goTo() {
    showProductSelect.value = false
}

function importSuccess(val: any) {
    visible.value = false
    gridOptions.data = val
}
function changeList(val: any[]) {
    gridOptions.data = cloneDeep(val)
    gridOptions.data.forEach((item: any) => item.quantity = 1)
}
</script>

<template>
    <ElSkeleton v-if="agreementLoading"
                :rows="5"
    />

    <template v-else>
        <div v-if="showProductSelect">
            <el-card mb-20>
                <ElButton @click="back">
                    返回
                </ElButton>

                <div class="info-title">
                    {{ agreementData?.agreementName }}
                </div>

                <el-form :model="detail"
                         :rules="rules"
                         label-width="auto"
                >
                    <el-row :gutter="20">
                        <el-col :span="6">
                            <el-form-item label="乙方:">
                                {{ agreementData?.partyB }}
                            </el-form-item>
                        </el-col>

                        <el-col :span="6">
                            <el-form-item label="合同开始时间:">
                                {{ agreementData?.startDate }}
                            </el-form-item>
                        </el-col>

                        <el-col :span="6">
                            <el-form-item label="合同结束时间:">
                                {{ agreementData?.endDate }}
                            </el-form-item>
                        </el-col>
                    </el-row>

                <!-- 清单附件下单暂时不做 -->
                <!-- <el-row>
                    <el-col :span="6">
                        <el-form-item label="通过清单附件下单:"
                                      prop="isFile"
                        >
                            <el-switch v-model="detail.isFile"
                                       inline-prompt
                                       active-text="启用"
                                       inactive-text="停用"
                                       class="is-file"
                            />
                        </el-form-item>
                    </el-col>
                </el-row> -->
                </el-form>
            </el-card>

            <el-card mb-20>
                <SearchTable ref="tableRef"
                             v-bind="gridOptions"
                >
                    <template #toolbar_buttons="{ row }">
                        <div class="list-tool">
                            <!-- 清单附件下单暂时不做 -->
                            <!-- <template v-if="detail.isFile">
                            <span class="info-title file-title">清单附件
                                <span class="info-tip">通过清单附件下单,必须上传清单附件</span>
                            </span>

                            <el-button type="primary"
                                       :icon="CirclePlus"
                            >
                                上传清单附件
                            </el-button>
                        </template> -->

                            <span class="info-title">商品列表</span>

                            <p>
                                <ButtonItem :btns="toolBtn"
                                            @btn-click="doAction($event, row)"
                                />
                            </p>
                        </div>
                    </template>

                    <!-- 清单附件下单暂时不做 -->
                    <!-- <template #fileInfo="{ row }">
                    <span style="color: #409EFF;cursor: pointer;"
                          @click="goOrderInfo(row)"
                    >
                        {{ `0408协议${row.name}` }}
                    </span>
                </template> -->

                    <template #info="{ row }">
                        <div class="pd-info">
                            <el-image v-if="row.skuUrl"
                                      style="width: 120px; height: 120px"
                                      class="mr-10"
                                      :src="row.skuUrl?.split(';')?.[0]"
                                      :preview-src-list="row.skuUrl?.split(';')"
                                      fit="cover"
                            />

                            <div class="pd-desc">
                                <p class="truncate w-full"
                                   :title="row?.productName"
                                >
                                    {{ row.productName }}
                                </p>

                                <p class="truncate w-full"
                                   :title="row?.skuName"
                                >
                                    规格：{{ row?.skuName }}
                                </p>

                                <p class="truncate w-full"
                                   :title="row?.category"
                                >
                                    品类：{{ row?.category }}
                                </p>

                                <p class="truncate w-full"
                                   :title="agreementData?.partyB"
                                >
                                    供应商：{{ agreementData?.partyB }}
                                </p>

                                <p class="truncate w-full"
                                   :title="row?.attribute"
                                >
                                    规格属性：{{ row?.attribute }}
                                </p>
                            </div>
                        </div>
                    </template>

                    <template #unit="{ row }">
                        <span style="color: red;">￥{{ row.agreementPrice }}元/{{ row?.unit }}</span>
                    </template>

                    <template #quantity="{ row }">
                        <el-input-number v-model="row.quantity"
                                         style="width: 100px;"
                                         :precision="0"
                                         :min="1"
                                         :max="99999"
                                         size="small"
                        />
                    </template>

                    <template #total="{ row }">
                        <span style="color: red;">￥{{ NP.round(row.agreementPrice * (row.quantity ?? 0), 2) }}元</span>
                    </template>

                    <template #operate="{ row }">
                        <ButtonItem :btns="btns"
                                    @btn-click="doAction($event, row)"
                        />
                    </template>
                </SearchTable>
            </el-card>

            <el-card>
                <div class="footer-btn">
                    <p>
                        共选择
                        <span style="color: red;">{{ gridOptions?.data?.length ?? 0 }}</span>

                        类商品,总价 <span style="color: red;margin-right: 20px;">￥{{ totalPrice }}元</span>

                        <ButtonItem :btns="footBtn"
                                    @btn-click="doAction($event)"
                        />
                    </p>
                </div>
            <!-- 清单附件下单暂时不做 -->
            <!-- <div v-else
                 class="footer-btn"
                 style="justify-content: flex-end;"
            >
                <el-button type="primary"
                           plain
                           @click="goTo"
                >
                    直接下单
                </el-button>
            </div> -->
            </el-card>

            <!-- 选择商品弹框 -->
            <SelectGoods ref="SelectGoodsRef"
                         v-model:show="show"
                         v-model:list="gridOptions.data"
                         :data="agreementData?.productList"
                         @change-list="changeList"
            />

            <!-- 导入商品 -->
            <UploadOrder v-model:visible="visible"
                         v-model:agreementId="agreementId"
                         @import-success="importSuccess"
            />
        </div>

        <DirectOrder v-else
                     v-model:showProductSelect="showProductSelect"
                     v-model:list="gridOptions.data"
                     v-model:orderId="orderId"
                     :agreement-meta-info="agreementData"
                     :order-data="orderData"
        />
    </template>
</template>

<style lang="less" scoped>
.info-title {
    font-size: 16px;
    font-weight: 600;
    line-height: 60px;
    margin-bottom: 20px;
}

.is-file {
    --el-switch-on-color: #13ce66;
    // --el-switch-off-color: #ff4949
}

.footer-btn {
    display: flex;
    justify-content: flex-end;

    > p {
        line-height: 30px;
    }
}

.list-tool {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .info-title {
        margin: 0;

        .info-tip {
            font-size: 14px;
        }
    }

    .file-title {
        &::before {
            content: '*';
            color: red;
            font-size: 21px;
            margin-right: 5px;
        }

        .info-tip {
            margin-left: 20px;

            &::before {
                content: '!';
                background: #dda451;
                color: #fff;
                margin-right: 5px;
                padding: 0 8px;
                border-radius: 11px;
            }
        }
    }
}

.pd-info {
    display: flex;
    // width: 100%;
    padding: 10px 0;

    img {
        width: 175px;
        margin-right: 20px;
    }

    .pd-desc {
        flex: 1;
        width: 1px;
        color: #9da1ae;
        text-align: left;
        display: flex;
        flex-direction: column;
        justify-content: space-between;

        p:first-child {
            font-size: 15px;
            color: #000;
            font-weight: 600;
        }
    }
}
</style>
